#!/bin/bash

# 方法 1: 使用 /proc/meminfo 解析内存信息
check_memory_proc_meminfo() {
  local phymem=$(awk '/^MemTotal:/{print $2}' /proc/meminfo)
  phymem=${phymem:-0}
  local min_mem_kb=$((1024 * 1024)) # 1024 MB in KB
  if [ "$phymem" -lt "$min_mem_kb" ]; then
    echo "Error: A minimum of 1024 MB RAM is required. (Using /proc/meminfo)" >&2
    return 1
  fi
  return 0
}

# 方法 2: 使用 free 命令解析内存信息
check_memory_free_command() {
  local phymem=$(free | awk '/^Mem:/{print $2}')
  phymem=${phymem:-0}
  local min_mem_kb=$((1024 * 1024)) # 1024 MB in KB
  if [ "$phymem" -lt "$min_mem_kb" ]; then
    echo "Error: A minimum of 1024 MB RAM is required. (Using free command)" >&2
    return 1
  fi
  return 0
}

# 方法 3: 使用 vmstat 命令解析内存信息
check_memory_vmstat_command() {
  if ! command -v vmstat &>/dev/null; then
    echo "Warning: vmstat command not found. Skipping this method." >&2
    return 2
  fi

  local phymem=$(vmstat -s | awk '/total memory/ {print $1}')
  phymem=${phymem:-0}
  local min_mem_kb=$((1024 * 1024)) # 1024 MB in KB
  if [ "$phymem" -lt "$min_mem_kb" ]; then
    echo "Error: A minimum of 1024 MB RAM is required. (Using vmstat command)" >&2
    return 1
  fi
  return 0
}

# Main 函数：依次测试每种方法
main() {
  echo "Testing memory check methods..."
  
  echo "Method 1: /proc/meminfo"
  if check_memory_proc_meminfo; then
    echo "Memory check passed using /proc/meminfo."
  fi

  echo "Method 2: free command"
  if check_memory_free_command; then
    echo "Memory check passed using free command."
  fi

  echo "Method 3: vmstat command"
  if check_memory_vmstat_command; then
    echo "Memory check passed using vmstat command."
  elif [ $? -eq 2 ]; then
    echo "Skipping vmstat method due to missing command."
  fi
}

# 调用主函数
main

